/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "se_defines.h"
#include "utils.h"

SE_GLOBALS()

void initialize_name(Input* input) {
  char buf[0x30];
  memset(buf, 0x0, sizeof(buf));
  auto str = input->read_string_n(sizeof(buf) - 1);
  strcpy(buf, str.c_str());
  printf("Name: %s\n", buf);
}

void initialize_age(Input* input, int** age_ptr) {
  struct padded_age {
    char pad[0x44];
    int age;
    char pad2[0x30];
  };
  padded_age pa;
  pa.age = input->read_int();
  if (pa.age < 0) {
    pa.age = -pa.age;
  }
  printf("Age: %d\n", pa.age);
  *age_ptr = &pa.age;
}

void test_case(std::string content) {
  Input input(reinterpret_cast<uint8_t*>(content.data()), content.size());

  int* age_ptr = nullptr;

  for (int i = 0; i < 2; i++) {
    switch (input.read_char()) {
      case 'n':
        initialize_name(&input);
        break;
      case 'a':
        initialize_age(&input, &age_ptr);
        break;
    }
  }

  if (age_ptr != nullptr && *age_ptr == -0x11111112) {
    SE_TARGET_STATE(true);
  }
}

int main(int argc, char* argv[]) {
  std::istream* input;
  std::ifstream file;
  if (argc < 2) {
    input = &std::cin; // No file name provided, read from stdin
  } else {
    file.open(argv[1]);
    if (!file) {
      std::cerr << "Could not open the file.\n";
      return 1;
    }
    input = &file; // File opened successfully, read from file
  }
  std::string content(
      (std::istreambuf_iterator<char>(*input)),
      std::istreambuf_iterator<char>());
  test_case(content);
  return 0;
}
